package com.css.zfzx.sjcj.modules.hddcA1InvRgnHasMaterialTable.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.constants.PlatformConstants;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.PlatformDateUtils;
import com.css.bpm.platform.utils.PlatformObjectUtils;
import com.css.bpm.platform.utils.PlatformPageUtils;
import com.css.bpm.platform.utils.PlatformSessionUtils;
import com.css.bpm.platform.utils.UUIDGenerator;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcA1InvRgnHasMaterialTable.repository.HddcA1InvrgnhasmaterialtableNativeRepository;
import com.css.zfzx.sjcj.modules.hddcA1InvRgnHasMaterialTable.repository.HddcA1InvrgnhasmaterialtableRepository;
import com.css.zfzx.sjcj.modules.hddcA1InvRgnHasMaterialTable.repository.entity.HddcA1InvrgnhasmaterialtableEntity;
import com.css.zfzx.sjcj.modules.hddcA1InvRgnHasMaterialTable.service.HddcA1InvrgnhasmaterialtableService;
import com.css.zfzx.sjcj.modules.hddcA1InvRgnHasMaterialTable.viewobjects.HddcA1InvrgnhasmaterialtablePageVO;
import com.css.zfzx.sjcj.modules.hddcA1InvRgnHasMaterialTable.viewobjects.HddcA1InvrgnhasmaterialtableQueryParams;
import com.css.zfzx.sjcj.modules.hddcA1InvRgnHasMaterialTable.viewobjects.HddcA1InvrgnhasmaterialtableVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 区域调查数据-调查区与面状资料关联表-属性表管理
 * @author zyb
 * @date 2020-11-30
 */
@Service
public class HddcA1InvrgnhasmaterialtableServiceImpl implements HddcA1InvrgnhasmaterialtableService {

    private final HddcA1InvrgnhasmaterialtableRepository hddcA1InvrgnhasmaterialtableRepository;
    private final HddcA1InvrgnhasmaterialtableNativeRepository hddcA1InvrgnhasmaterialtableNativeRepository;
    private final ResearchAreaPlanarDataExcelVerifyHandler researchAreaPlanarDataExcelVerifyHandler;

    @Autowired
    public HddcA1InvrgnhasmaterialtableServiceImpl(HddcA1InvrgnhasmaterialtableRepository hddcA1InvrgnhasmaterialtableRepository,
                                                   HddcA1InvrgnhasmaterialtableNativeRepository hddcA1InvrgnhasmaterialtableNativeRepository,
                                                   ResearchAreaPlanarDataExcelVerifyHandler researchAreaPlanarDataExcelVerifyHandler) {
        this.hddcA1InvrgnhasmaterialtableRepository = hddcA1InvrgnhasmaterialtableRepository;
        this.hddcA1InvrgnhasmaterialtableNativeRepository = hddcA1InvrgnhasmaterialtableNativeRepository;
        this.researchAreaPlanarDataExcelVerifyHandler = researchAreaPlanarDataExcelVerifyHandler;
    }

    @Override
    public JSONObject queryHddcA1Invrgnhasmaterialtables(HddcA1InvrgnhasmaterialtableQueryParams queryParams, int curPage, int pageSize, String sort, String order) {
        Page<HddcA1InvrgnhasmaterialtablePageVO> hddcA1InvrgnhasmaterialtablePage = this.hddcA1InvrgnhasmaterialtableNativeRepository.queryHddcA1Invrgnhasmaterialtables(queryParams, curPage, pageSize, sort, order);
        return PlatformPageUtils.formatPageData(hddcA1InvrgnhasmaterialtablePage);
    }


    @Override
    public HddcA1InvrgnhasmaterialtableEntity getHddcA1Invrgnhasmaterialtable(String id) {
        return this.hddcA1InvrgnhasmaterialtableRepository.findById(id).orElse(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcA1InvrgnhasmaterialtableEntity saveHddcA1Invrgnhasmaterialtable(HddcA1InvrgnhasmaterialtableEntity hddcA1Invrgnhasmaterialtable) {
        hddcA1Invrgnhasmaterialtable.setUuid(UUIDGenerator.getUUID());
        hddcA1Invrgnhasmaterialtable.setCreateUser(PlatformSessionUtils.getUserId());
        Timestamp now = PlatformDateUtils.getCurrentTimestamp();
        hddcA1Invrgnhasmaterialtable.setCreateTime(now);
        hddcA1Invrgnhasmaterialtable.setUpdateTime(now);
        hddcA1Invrgnhasmaterialtable.setIsValid(PlatformConstants.Y);
        hddcA1Invrgnhasmaterialtable.setQualityinspectionStatus(PlatformConstants.N);
        hddcA1Invrgnhasmaterialtable.setExtends10(PlatformConstants.Y);
        this.hddcA1InvrgnhasmaterialtableRepository.save(hddcA1Invrgnhasmaterialtable);
        return hddcA1Invrgnhasmaterialtable;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcA1InvrgnhasmaterialtableEntity updateHddcA1Invrgnhasmaterialtable(HddcA1InvrgnhasmaterialtableEntity hddcA1Invrgnhasmaterialtable) {
        HddcA1InvrgnhasmaterialtableEntity entity = hddcA1InvrgnhasmaterialtableRepository.findById(hddcA1Invrgnhasmaterialtable.getUuid()).get();
        UpdateUtil.copyNullProperties(entity, hddcA1Invrgnhasmaterialtable);
        hddcA1Invrgnhasmaterialtable.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcA1Invrgnhasmaterialtable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcA1InvrgnhasmaterialtableRepository.save(hddcA1Invrgnhasmaterialtable);
        return hddcA1Invrgnhasmaterialtable;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcA1Invrgnhasmaterialtables(List<String> ids) {
        List<HddcA1InvrgnhasmaterialtableEntity> hddcA1InvrgnhasmaterialtableList = this.hddcA1InvrgnhasmaterialtableRepository.findAllById(ids);
        if (!PlatformObjectUtils.isEmpty(hddcA1InvrgnhasmaterialtableList) && hddcA1InvrgnhasmaterialtableList.size() > 0) {
            for (HddcA1InvrgnhasmaterialtableEntity hddcA1Invrgnhasmaterialtable : hddcA1InvrgnhasmaterialtableList) {
//                this.hddcA1InvrgnhasmaterialtableRepository.delete(hddcA1Invrgnhasmaterialtable);
                hddcA1Invrgnhasmaterialtable.setIsValid(PlatformConstants.N);
                hddcA1Invrgnhasmaterialtable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcA1Invrgnhasmaterialtable.setUpdateTime(new Date());
                this.hddcA1InvrgnhasmaterialtableRepository.save(hddcA1Invrgnhasmaterialtable);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        return PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
    }

    @Override
    public void exportFile(HddcA1InvrgnhasmaterialtableQueryParams queryParams, HttpServletResponse response) {
        List<HddcA1InvrgnhasmaterialtableEntity> yhDisasterEntities = hddcA1InvrgnhasmaterialtableNativeRepository.exportYhDisasters(queryParams);
        List<HddcA1InvrgnhasmaterialtableVO> list = new ArrayList<>();
        for (HddcA1InvrgnhasmaterialtableEntity entity : yhDisasterEntities) {
            HddcA1InvrgnhasmaterialtableVO yhDisasterVO = new HddcA1InvrgnhasmaterialtableVO();
            BeanUtils.copyProperties(entity, yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list, "调查区与面状资料关联表", "调查区与面状资料关联表",
                HddcA1InvrgnhasmaterialtableVO.class, "调查区与面状资料关联表.xls", response);
    }

    @Override
    public String importExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            params.setVerifyHandler(researchAreaPlanarDataExcelVerifyHandler);
            // 获取到Excel数据
            ExcelImportResult<HddcA1InvrgnhasmaterialtableVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcA1InvrgnhasmaterialtableVO.class, params);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                for (HddcA1InvrgnhasmaterialtableVO yhDisasterVO : result.getFailList()) {
                    returnMsg.append("第").append(yhDisasterVO.getRowNum()).append("行").append(yhDisasterVO.getErrorMsg()).append("<br/>");
                }
                if (returnMsg.length() > 0)
                    return returnMsg.toString();
            }
            List<HddcA1InvrgnhasmaterialtableVO> list = result.getList();
            //保存
            saveDisasterList(list);
            return returnMsg.append("成功导入").append(result.getList().size()).toString();
        } catch (Exception e) {
            return "导入失败，请检查数据正确性";
        }
    }

    /**
     * 逻辑删除-根据项目id删除数据
     */
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcA1InvrgnhasmaterialtableEntity> hddcA1InvrgnhasmaterialtableList = this.hddcA1InvrgnhasmaterialtableRepository.queryHddcA1InvrgnhasmaterialtablesByProjectId(projectIds);
        if (!PlatformObjectUtils.isEmpty(hddcA1InvrgnhasmaterialtableList) && hddcA1InvrgnhasmaterialtableList.size() > 0) {
            for (HddcA1InvrgnhasmaterialtableEntity hddcA1Invrgnhasmaterialtable : hddcA1InvrgnhasmaterialtableList) {
                hddcA1Invrgnhasmaterialtable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcA1Invrgnhasmaterialtable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcA1Invrgnhasmaterialtable.setIsValid(PlatformConstants.N);
                this.hddcA1InvrgnhasmaterialtableRepository.save(hddcA1Invrgnhasmaterialtable);
            }
        }
    }

    /**
     * 逻辑删除-根据任务id删除数据
     */
    @Override
    public void deleteByTaskId(List<String> taskIds) {
        List<HddcA1InvrgnhasmaterialtableEntity> hddcA1InvrgnhasmaterialtableList = this.hddcA1InvrgnhasmaterialtableRepository.queryHddcA1InvrgnhasmaterialtablesByTaskId(taskIds);
        if (!PlatformObjectUtils.isEmpty(hddcA1InvrgnhasmaterialtableList) && hddcA1InvrgnhasmaterialtableList.size() > 0) {
            for (HddcA1InvrgnhasmaterialtableEntity hddcA1Invrgnhasmaterialtable : hddcA1InvrgnhasmaterialtableList) {
                hddcA1Invrgnhasmaterialtable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcA1Invrgnhasmaterialtable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcA1Invrgnhasmaterialtable.setIsValid(PlatformConstants.N);
                this.hddcA1InvrgnhasmaterialtableRepository.save(hddcA1Invrgnhasmaterialtable);
            }
        }
    }

    /**
     * 批量存入库表并且返回错误数量
     */
    public void saveDisasterList(List<HddcA1InvrgnhasmaterialtableVO> list) {
        for (HddcA1InvrgnhasmaterialtableVO hddcA1InvrgnhasmaterialtableVO : list) {
            HddcA1InvrgnhasmaterialtableEntity yhDisasterEntity = new HddcA1InvrgnhasmaterialtableEntity();
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(hddcA1InvrgnhasmaterialtableVO, yhDisasterEntity);
            saveHddcA1Invrgnhasmaterialtable(yhDisasterEntity);
        }
    }
}
